package com.hrt.common.safe;

import com.btcode.web.core.unit.URLUtil;
import com.btcode.web.safe.service.IVerifyService;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.ServletRequest;

public abstract class BaseVerifyService implements IVerifyService {

    /**
     * 免验证地址列表
     */
    protected List<String> exceptURL = new ArrayList<>();

    @Override
    public Object getUser(ServletRequest request) {

        IUser user = UserSessionManager.getInstance().getUser();
        return user;
    }

    /**
     * 增加例外免验证地址
     */
    public void addExceptURL(String url) {

        exceptURL.add(url);
    }

    /**
     * 是否可以免验证访问
     */
    public boolean canAccessWithoutAuthentication(ServletRequest request) {

        String requestUrl = URLUtil.getURLWithoutProjectName(request);

        for (String url : exceptURL) {
            if (requestUrl.equals(url)) {
                return true;
            }
            if (matchUrl(requestUrl, url)) {
                return true;
            }
        }
        return false;
    }

    protected boolean matchUrl(String requestUrl, String functionUrl) {

        if (functionUrl.contains("*")) {
            functionUrl = functionUrl.replaceAll("/", "\\/").replaceAll("\\*", ".*?");
            Pattern pattern = Pattern.compile(functionUrl);
            Matcher matcher = pattern.matcher(requestUrl);
            if (matcher.matches()) {
                return true;
            }
        }
        return false;
    }

}
